package com.xybian.config;

import com.xybian.filter.JwtAuthenticationTokenFilter;
import com.xybian.handler.MyAccessDeniedHandler;
import com.xybian.handler.MyAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 安全配置
 *
 * @author SongRenShuo
 * @date 2023-12-23
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启方法级别的权限控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationTokenFilter tokenFilter;

    @Autowired
    private MyAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private MyAccessDeniedHandler accessDeniedHandler;

    /**
     * 创建 BCryptPasswordEncoder 注入容器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    /**
     * 为登录接口 提供下一步 调用的方法
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 配置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 关闭 csrf
                .csrf().disable()
                // 不通过 session 获取 SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对登录接口  允许匿名访问  /user/login
                .antMatchers("/user/login").anonymous()
                // 配置权限
                //.antMatchers("/hello").hasAuthority("test")
                // 除上面外的所有请求全部需要 鉴权认证
                .anyRequest().authenticated();


        // 定义filter的先后顺序，保证 jwtFilter比用户验证的过滤器先执行
        http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 自定义异常捕获机制
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);

        // 允许跨域
        http.cors();
    }
}
